<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/20
 * Time: 下午8:46
 */

namespace App\Http\Controllers;

use App\Http\Model\AdJust;
use App\Http\Model\HopeLuckDraw;
use App\Http\Model\LuckDraw;
use App\Http\Model\System;
use App\Http\Model\User;
use App\Http\Model\WishDefender;
use App\Http\Model\WishWheel;
use App\Http\Services\AppleAsaReportServices;
use App\Http\Services\GiftServices;
use App\Http\Services\MallServices;
use App\Http\Services\MsgServices;
use App\Http\Services\SystemServices;
use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Lib\Response;
use App\Http\Services\UserServices;
use App\Lib\Publisher;
use Illuminate\Http\Request;
use App\Lib\map;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Http\Services\DeviceServices;
use App\Http\Services\UploadServices;

class SystemController  extends BaseController
{
    private $services_system;
    private $services_gift;
    private $services_mall;
    private $msg_service;
    private $services_user;
    protected $deviceServices;
    protected $helpServices;

    public function __construct(SystemServices $systemServices, GiftServices $giftServices, MallServices $mallServices,MsgServices $msg_service, UserServices $userServices,DeviceServices $deviceServices){
        $this->services_system = $systemServices;
        $this->services_gift = $giftServices;
        $this->services_mall = $mallServices;
        $this->msg_service = $msg_service;
        $this->services_user = $userServices;
        $this->deviceServices = $deviceServices;
    }

    public function get_init(Request $request){
        $platform_id = (int) $request->get("platform_id");
        $channel_id = (int) $request->get("channel_id");
        $version_id = (string) $request->get("version_id");
        $version_code = (string) $request->get("version_code");

        if(!$platform_id || !$channel_id || !$version_id){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $app_ua = $this->services_system->parse_app_UA();

        $userInfo = $this->services_user->get_current_user();
        $userId = $userInfo['user_id'] ?? 0;
        if($userId) {
            $this->services_user->setOsVersion($userId, $app_ua['version_no']);
        }

        $configMap = [];
        $config = $this->services_system->get_config();
        foreach ($config as $k => $v){
            $value = $v['value'];
            if ($v['type'] == 1){
                $value = intval($v['value']);
            }
            $configMap[$k] = $value;
        }

        //更新用户渠道
        $this->services_user->update_channel_guid();

        //当前用户
        $userInfo = $this->services_user->get_current_user();
        $userId = $userInfo['user_id'] ?? 0;

        $data = [];
        $data['time'] = time();

        //版本更新
        $data['version'] = $this->services_system->get_last_version($platform_id, $channel_id);
        //青少年
        $data['teenager'] = isset($configMap['teenager']) ? $configMap['teenager'] : 0;
        $data['teenager_policy'] = isset($configMap['teenager_policy']) ? $configMap['teenager_policy'] : '';
        //用户注册协议
        $data['user_protocol_url'] = isset($configMap['user_protocol_url']) ? $configMap['user_protocol_url'] : '';
        //隐私协议
        $data['policy_url'] = isset($configMap['policy_url']) ? $configMap['policy_url'] : '';
        //房间提醒内容
        $data['room_remind'] = isset($configMap['room_remind']) ? $configMap['room_remind'] : '';
        //全服信息
        $data['chat_room_id'] = config('rong_cloud.chat_room_id');
        //客服url
        $data['kefu_url'] = isset($configMap['kefu_url']) ? $configMap['kefu_url'] : '';
        //充值协议
        $data['recharge_protocol'] = isset($configMap['recharge_protocol']) ? $configMap['recharge_protocol'] : '';
        //注销规则
        $data['account_cancel_url'] = isset($configMap['account_cancel_url']) ? $configMap['account_cancel_url'] : '';
        //h5充值url
        $data['h5_recharge_url'] = isset($configMap['h5_recharge_url']) ? $configMap['h5_recharge_url'] : '';
        //h5提现url
        $data['h5_withdraw_url'] = isset($configMap['h5_withdraw_url']) ? $configMap['h5_withdraw_url'] : '';
        //公会细则
        $data['union_help_url'] = isset($configMap['union_help_url']) ? $configMap['union_help_url'] : '';
        //分享h5链接
        $data['share_h5_url'] = isset($configMap['share_h5_url']) ? $configMap['share_h5_url'] : '';

        //金币兑换钻石比例
        $config = config('pay');
        $kk_to_diamond = $config['wallet_change_ratio']['kk_to_diamond'];
        $data['kk_to_diamond'] = $kk_to_diamond;

        //邀请相关
        $data['share_invite_url'] = isset($configMap['share_invite_url']) ? $configMap['share_invite_url'] : '';
        $data['open_code_url'] = "";
        $queryStr = '?';
        if (!empty($data['share_invite_url'])){
            $queryStr = parse_url($data['share_invite_url'], PHP_URL_QUERY) ? '&' : '?';
        }
        if ($userInfo && $userInfo['is_open_code'] == 1) {
            $data['open_code_url'] = $data['share_invite_url'] . $queryStr .'user_id='.$userId;
        }
        $data['open_code']['is_open_code'] = $userInfo['is_open_code'] == 1 ? 1 : 0;
        $data['open_code']['share']['title'] = isset($configMap['share_invite_title']) ? $configMap['share_invite_title'] : '';
        $data['open_code']['share']['msg'] = isset($configMap['share_invite_msg']) ? $configMap['share_invite_msg'] : '';
        $data['open_code']['share']['image'] = isset($configMap['share_invite_image']) ? build_image($configMap['share_invite_image']) : '';
        $data['open_code']['share']['url'] = $data['share_invite_url'] . $queryStr .'user_id='.$userId;

        //财富等级地址
        $data['finance_rank_url'] = isset($configMap['finance_rank_url']) ? $configMap['finance_rank_url'] : '';
        //提现协议
        $data['extract_protocol'] = isset($configMap['extract_protocol']) ? $configMap['extract_protocol'] : '';
        //提现协议
        $data['extract_rule'] = isset($configMap['extract_rule']) ? $configMap['extract_rule'] : '';

        Response::returnResult(Hint::SUCCESS, $data);
    }

    public function get_version(Request $request){
        if(!$request->get('platform_id')){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if(!$request->get('channel_id')){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $platform_id = $request->get("platform_id");
        $channel_id = $request->get("channel_id");
        $version_id = (string) $request->get("version_id");
        $version_code = (string) $request->get("version_code");

        $version_item = $this->services_system->get_last_version($platform_id, $channel_id);
        if (empty($version_item)){
            Response::returnResult(Hint::SYSTEM_NOVER);
        }
        if (version_compare($version_item['version_id'] , $version_id) <= 0){
            Response::returnResult(Hint::SYSTEM_NOVER);
        }

        //判断当前是否是最新版本
        $version_item['is_new'] = $version_id == $version_item['version_id'];
        Response::returnResult(Hint::SUCCESS, $version_item);
    }

    /**
     * 可选心情列表
     */
    public function moodList(){
        $data = $this->services_system->moodList();
        Response::returnResult(Hint::SUCCESS, $data);
    }


    public function get_expression_version(Request $request){
        $version_item = $this->services_system->get_expression_last_version();
        if (empty($version_item)){
            Response::returnResult(Hint::SYSTEM_NOVER, []);
            return;
        }
        Response::returnResult(Hint::SUCCESS, $version_item);
    }

    public function get_expression_new_version(Request $request){
        $version_item = $this->services_system->get_expression_new_last_version();
        if (empty($version_item)){
            Response::returnResult(Hint::SYSTEM_NOVER, []);
            return;
        }
        Response::returnResult(Hint::SUCCESS, $version_item);
    }

    /**
     * 文件上传获取路径
     */
    public function get_put_file_url(Request $request){
        if(!$request->get("type")){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if(!$request->get("exts")){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $type = $request->get("type");
        $exts = $request->get("exts");

        $data = $this->services_system->get_put_file_url($type, $exts);
        if($data == null){
            Response::returnResult(Hint::LOGIN_OUT);
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 文件上传获取路径
     */
    public function get_put_file_url_manage(Request $request){
        $aes = $request->get("noase") > 0 ? 0 : 1;
        if(!$request->get("type")){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if(!$request->get("exts")){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $type = $request->get("type");
        $exts = $request->get("exts");

        $data = $this->services_system->get_put_file_url($type, $exts);
        if($data == null){
            Response::returnResult(Hint::LOGIN_OUT);
        }
        Response::returnResult(Hint::SUCCESS, $data, '', 0);
    }

    /**
     * 获取当前位置信息
     * @param Request $request
     */
    public function get_locations(Request $request){
        $lng = $request->get("lng");
        $lat = $request->get("lat");
        $word = $request->get("word");
        $map = new map();
        if (empty($lng) || empty($lat)){
            $ip = client_ip();
            $local = $map->get_location($ip);
            $lng = $local['lng'];
            $lat = $local['lat'];
        }
        $data = [];
        if (empty($word)){
            $data = $map->get_pois($lng, $lat);
        }
        else{
            $data = $map->get_search_pois($word, $lng, $lat);
        }
        if (empty($data)){
            $data = [];
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 清除缓存
     * @param Request $request
     */
    public function clear_cache(Request $request){
        $this->msg_service->set_cross();
        $type = (int) $request->post("type", 0);
        if(!$type){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $this->services_system->clear_cache($type);
    }

    /**
     * 版本升级通知
     * @param Request $request
     */
    public function release_version(Request $request){
        $this->msg_service->set_cross();
        $id = (int) $request->post('id',0);
        $this->msg_service->release_version($id);
    }

    /**
     * 根据获取版本数据
     * */
    public function getSystemVersion()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'getSystemVersion', $this->requestData,false);

        } while (false);

        $this->responseData();
    }

    ################# 统一验证码模块 ##########################################

    /**
     * 获取图形验证码
     * */
    public function captchaCode()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'captchaCode', $this->requestData, false);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 校验图形验证码
     * */
    public function checkCaptchaCode()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'checkCaptchaCode', $this->requestData, false);

            // TODO 校验成功
            if ($this->responseData['code'] == Hint::SUCCESS) {
                // TODO 记录操作手机号时间
                $this->services_system->requestData['phone'] = $this->responseData['data']['phone'];
                $this->services_system->recordPhoneOpTime();
            }

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    ################# 后台调用 ##########################################

    /**
     * 系统配置创建
     * */
    public function configCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'configCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 系统配置更新
     * */
    public function configUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'configUpdate', $this->requestData);

        } while (false);
        write_log('SystemController', 'configUpdate', array('param'=>$this->requestData, 'time'=>time()));
        $this->responseData();
    }

    /**
     * 系统配置删除
     * */
    public function configRemove()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'configRemove', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 系统版本创建
     * */
    public function versionCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'versionCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 系统版本更新
     * */
    public function versionUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'versionUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 系统版本删除
     * */
    public function versionRemove()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'versionRemove', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 列表
     * */
    public function getHelpList()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'getHelpList', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 收集用户信息
     * */
    public function pushUserInfo()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'pushUserInfo', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 根据渠道号获取指定跳转房间
     */
    public function getRoomIdByChannel()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            //$this->callCommon($this->services_system, 'getRoomIdByChannel', $this->requestData);
            $this->callCommon($this->services_system, 'getRoomIdByChannelV2', $this->requestData);
        } while (false);
        $this->responseData();
    }

    /**
     * 获取渠道跳房间列表
     */
    public function getChannelRoomIdList()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'getChannelRoomIdList', $this->requestData);
        } while (false);
        $this->responseData();
    }

    /**
     * 设置渠道号指定跳转的房间 免登录
     */
    public function setChannelRoomCms()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'setChannelRoomId', $this->requestData);
        } while (false);

        $this->responseData();
    }

    /**
     * 设置渠道号指定跳转的房间
     */
    public function setChannelRoomId()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->services_system, 'setChannelRoomId', $this->requestData);
        } while (false);
        $this->responseData();
    }

    /**
     * 删除渠道号指定跳转的房间
     */
    public function delChannelRoom()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'delChannelRoomDel', $this->requestData);
        } while (false);
        $this->responseData();
    }

    //后台设置首页配置

    public function updateOrInsertHome(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'updateOrInsertHome', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 获取系统说明信息
     */
    public function getExplain(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'getExplain', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 新增房间推荐比例
     */
    public function addProportion()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'addProportion', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间快捷消息文本
     */
    public function getRoomFastMsg(){
        $data = $this->services_system->getRoomFastMsg();
        Response::returnResult(Hint::SUCCESS ,$data);
    }

    /**
     * 文件上传
     * @param $request
     * @param $uploadServices
     * @return mixed
     */
    public function ossFileUpload(Request $request, UploadServices $uploadServices) {
        $isMd5 = $request->post('md5', 1);
        $extension = $uploadServices->get_ext();
        $config = $this->services_system->get_put_file_url($_POST['type'] ?? 19, $extension);
        $res = $uploadServices->upload($isMd5, $config);
        if($res === Hint::PARAM_ERROR) Response::returnResult(Hint::PARAM_ERROR);
        if($res === Hint::FILE_UPLOAD_CONFIG_ERR) Response::returnResult(Hint::FILE_UPLOAD_CONFIG_ERR);
        Response::returnResult(Hint::SUCCESS, $res);
    }

    /**
     * 苹果广告标识上报
     */
    public function postAsaReport(Request $request) {
        $this->services_system->postAsaReport($request->except('_url'));
        return Response::returnResult(Hint::SUCCESS);
    }

    /**
     * Apple ASA自归因业务
     *
     * Created at 2021/12/2 13:51
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     */
    public function postAsaReportV2(Request $request)
    {
        $token = $request->input('token', '');
        $idfa = $request->input('idfa', '');
        (new AppleAsaReportServices())->dealAsaReport($token, $idfa);//token是APP端提供的
        Response::returnResult(Hint::SUCCESS);
    }

    public function getAdjust(Request $request) {
        $all = $request->input();

        $model = new AdJust();
        $model->createAdjust([
            'gps_adid' => $all['gps_adid'] ?? '',
            'idfa' => $all['idfa'] ?? '',
            'idfv' => $all['idfv'] ?? '',
            'adid' => $all['adid'] ?? '',
            'tracker' => $all['tracker'] ?? '',
            'tracker_name' => $all['tracker_name'] ?? '',
            'app_name' => $all['app_name'] ?? '',
            'activity_kind' => $all['activity_kind'] ?? '',
            'created_at' => $all['created_at'] ?? 0,
            'event_token' => $all['event_token'] ?? '',
            'event_name' => $all['event_name'] ?? '',
            'impression_time' => $all['impression_time'] ?? 0,
            'impression_time_hour' => $all['impression_time_hour'] ?? 0,
            'click_time' => $all['click_time'] ?? 0,
            'click_time_hour' => $all['click_time_hour'] ?? 0,
            'installed_at' => $all['installed_at'] ?? 0,
            'installed_at_hour' => $all['installed_at_hour'] ?? 0,
            'reattributed_at' => $all['reattributed_at'] ?? 0,
            'reattributed_at_hour' => $all['reattributed_at_hour'] ?? 0,
            'first_tracker' => $all['first_tracker'] ?? '',
            'last_tracker' => $all['last_tracker'] ?? '',
            'last_tracker_name' => $all['last_tracker_name'] ?? '',
            'uninstalled_at' => $all['uninstalled_at'] ?? 0,
            'reinstalled_at' => $all['reinstalled_at'] ?? 0,
            'last_session_time' => $all['last_session_time'] ?? 0,
            'rejection_reason' => $all['rejection_reason'] ?? '',
            'outdated_tracker_token' => $all['outdated_tracker_token'] ?? '',
            'attribution_updated_at' => $all['attribution_updated_at'] ?? 0,
            'app_version' => $all['app_version'] ?? '',
            'hardware_name' => $all['hardware_name'] ?? '',
            'android_id' => $all['android_id'] ?? '',
            'oaid' => $all['oaid'] ?? '',
            'user_agent' => $all['user_agent'] ?? '',
            'ip_address' => $all['ip_address'] ?? '',
            'city' => $all['city'] ?? '',
            'os_name' => $all['os_name'] ?? '',
            'platform' => $all['platform'] ?? '',
            'os_version' => $all['os_version'] ?? '',
            'll_user_id' => intval($all['ll_user_id'] ?? 0),
            'll_register_user_id' => intval($all['ll_register_user_id'] ?? 0),
            'change_time' => time()
        ]);

        $all = json_encode($all);
        write_log("adjust", "adjust", $all);

        Response::returnResult(Hint::SUCCESS);
    }
    public function pushClick(Request $request){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'pushClick', $this->requestData);

        } while (false);

        $this->responseData();
    }
    public function getPushClickLog(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'getPushClickLog');

        } while (false);

        $this->responseData();
    }
    public function delPushClickLog(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_system, 'delPushClickLog');

        } while (false);

        $this->responseData();
    }

    public function forbidIp(Request $request) {
        /*
        $ip = $request->post('ip', '');
        $status = $request->post('status', 0);
        $operateInfo = $request->post('operate_info', '');
        $expireAt = (int) $request->post('expire_at', 0);
        $uuid = (string) $request->post('uuid', '');
        $this->services_system->forbidIp($ip, $status, $operateInfo, $expireAt, $uuid);
        Response::returnResult(Hint::SUCCESS);
        */
    }

    public function setNavMenu(Request $request){
        $key = $request->input('key');
        if(!$key) {
            return Response::returnResult(Hint::PARAM_ERROR);
        }
        $value = $request->input('value');
        if(!$value) {
            return Response::returnResult(Hint::PARAM_ERROR);
        }
        $res = $this->services_system->setNavMenu($key,$value);
        if ($res){
            $this->services_system->setNavMenuRedis();
            Response::returnResult(Hint::SUCCESS);
        }
            Response::returnResult(Hint::ERROR);
    }

    public function delNavMenu (Request $request){
        $ids = $request->input('id');
        if (!$ids){
            return Response::returnResult(Hint::PARAM_ERROR);
        }
        $idArr = explode(',',$ids);
        foreach ($idArr as $id){
            $this->services_system->delNavMenu($id);
        }
        $this->services_system->setNavMenuRedis();
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * @desc 亚创需要上报用户房间等数据，他们又不能搭建nginx服务器，所以只能埋点
     * @date 2021/01/24
     * @Author zxiaofee
     * @param Request $request
     */
    public function aigReport(Request $request){
        $user_id = $request->input('user_id')??"0";
        $room_id = $request->input('room_id')??"0";
        $platform = $request->input('platform')??"0";
        $version = $request->input('version')??"0";
        $time = $request->input('time')??"0";

        write_log("aigReport", "user_data_report", [
            'Userid' => $user_id,
            'Roomid' => $room_id,
            'Platform' => $platform,
            'Version' => $version,
            'Time' => $time,
        ]);

        Response::returnResult(Hint::SUCCESS);
    }

    public function getConfig()
    {
        $config = $this->services_system->get_config();
        $data = [];
        foreach ($config as $k => $v){
            $value = $v['value'];
            if ($v['type'] == 1){
                $value = intval($v['value']);
            }
            $data[$k] = $value;
        }

        Response::returnResult(Hint::SUCCESS ,$data);
    }

}
